<template>
  <div class="booking-page">
    <div class="banner">
      <h1>预约咨询</h1>
      <p>专业贴心的服务，为您的心理健康保驾护航</p>
    </div>
    <el-tabs v-model="activeTab" class="tabs">
      <el-tab-pane label="线下咨询" name="offline">
        <!-- 咨询师滚动区域 -->
        <div class="therapist-scroll-section">
          <h3>咨询师信息</h3>
          <div class="therapist-container">
            <button class="scroll-button left" @click="scrollLeft">
              <el-icon><ArrowLeft /></el-icon>
            </button>
            <div class="scrollbar-wrapper">
              <div class="therapist-list">
                <div
                  v-for="therapist in therapists"
                  :key="therapist.id"
                  class="therapist-card"
                  :class="{ 'selected': therapist.id === selectedTherapist?.id }"
                  @click="selectTherapist(therapist)"
                >
                  <img :src="therapist.avatar" :alt="therapist.name" />
                  <h4>{{ therapist.name }}</h4>
                  <p>{{ therapist.title }}</p>
                  <p>{{ therapist.description }}</p>
                </div>
              </div>
            </div>
            <button class="scroll-button right" @click="scrollRight">
              <el-icon><ArrowRight /></el-icon>
            </button>
          </div>
        </div>
        <!-- 日历和时间段区域 -->
        <div class="booking-container">
          <div class="calendar-section">
            <el-calendar v-model="selectedDate" :disabled-date="isDateDisabled" class="calendar" />
          </div>
          <div class="details-section">
            <div class="time-slots">
              <h3>可预约时段</h3>
              <el-button
                v-for="time in timeSlots"
                :key="time"
                :type="selectedTime === time ? 'primary' : 'default'"
                :disabled="!isTimeAvailable(time)"
                @click="selectedTime = time"
              >
                {{ time }}
              </el-button>
            </div>
          </div>
        </div>
      </el-tab-pane>

      <el-tab-pane label="线上咨询" name="online">
        <p>线上咨询功能开发中...</p>
      </el-tab-pane>
    </el-tabs>

    <div class="additional-info">
      <h3>填写信息</h3>
      <el-input v-model="contactInfo.phone" placeholder="请输入手机号" />
      <el-input
        v-model="problemDescription"
        type="textarea"
        placeholder="简单描述您的问题"
        :rows="4"
      />
    </div>

    <div class="footer">

      <el-button type="primary" @click="handleSubmit">确认预约</el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Api } from '@/api'
import defaultImage from '@/assets/zhishi.png' // 引入默认图片
import { useUserStore } from '@/stores/user.js';
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue'

const userStore = useUserStore();
const token = ref(userStore.token);


const activeTab = ref('offline') // 默认激活的标签页，线下咨询
const selectedDate = ref(null)
const selectedTime = ref(null)
const selectedTherapist = ref(null) // 咨询师

// 咨询师数据
const therapists = ref([])
const loadingTherapists = ref(true)
const therapistsError = ref(null)

const timeSlots = ref([]) // 当前选中日期的可用时段
const availableDates = ref([]) // 咨询师所有有空闲的日期
const counselorFreeTimeMap = ref({})
const contactInfo = ref({ phone: '', email: '' })
const problemDescription = ref('')

// 直接写死 room_number
const roomNumber = 1;

const scrollContainer = ref(null)
const scrollStep = 300

const scrollLeft = () => {
  const container = document.querySelector('.scrollbar-wrapper')
  if (container) {
    container.scrollLeft -= scrollStep
  }
}

const scrollRight = () => {
  const container = document.querySelector('.scrollbar-wrapper')
  if (container) {
    container.scrollLeft += scrollStep
  }
}

const appointments = ref([])

// 获取预约列表
const fetchAppointments = async () => {
  try {
    const response = await Api.getAllAppointments()
    if (response.data.status === 200) {
      appointments.value = response.data.data.appointments
    }
  } catch (error) {
    console.error('获取预约列表失败:', error)
  }
}

onMounted(() => {
  console.log('Token:', token.value);
  fetchTherapists() // 获取咨询师数据
  fetchAppointments() // 获取预约列表
})

// 从后端获取咨询师数据
const fetchTherapists = async () => {
  try {
    loadingTherapists.value = true
    const response = await Api.getAllUsers({})
    console.log('获取到的用户数据:', response.data)
    if (response.data && Array.isArray(response.data.data.users)) {
      // 直接加载所有咨询师，不进行任何限制
      therapists.value = response.data.data.users
        .filter((user) => user.is_counselor)
        .map((therapist) => ({
          ...therapist,
          avatar: therapist.avatar ? `http://localhost:4000${therapist.avatar}` : defaultImage,
          description: therapist.introduction || '暂无简介',
        }))
      console.log('过滤后的咨询师数据:', therapists.value)
    } else {
      console.error('后端返回的咨询师数据格式不正确:', response.data)
      throw new Error('咨询师数据格式错误')
    }
  } catch (error) {
    console.error('获取咨询师数据失败:', error)
    therapistsError.value = '加载咨询师数据失败，请稍后再试'
  } finally {
    loadingTherapists.value = false
  }
}

// 点击咨询师卡片时的处理函数
const selectTherapist = async (therapist) => {
  selectedTherapist.value = therapist;
  selectedTime.value = null;
  selectedDate.value = null;
  try {
    const response = await Api.getCounselorFreeTime({ counselor_id: therapist.id });
    if (response.data.status === 200) {
      const arr = response.data.data;
      const map = {};
      const dates = [];
      if (Array.isArray(arr)) {
        arr.forEach(item => {
          map[item.date] = item.time_slots;
          if (item.time_slots && item.time_slots.length > 0) dates.push(item.date);
        });
      }
      counselorFreeTimeMap.value = map;
      availableDates.value = dates;
      timeSlots.value = [];
      if (dates.length > 0) {
        selectedDate.value = new Date(dates[0]);
      }
    } else {
      ElMessage.error(response.data.message || '获取咨询师空闲时间失败');
      counselorFreeTimeMap.value = {};
      availableDates.value = [];
      timeSlots.value = [];
    }
  } catch {
    ElMessage.error('获取咨询师空闲时间失败，请稍后再试');
    counselorFreeTimeMap.value = {};
    availableDates.value = [];
    timeSlots.value = [];
  }
};

const isDateDisabled = (date) => {
  const d = date.toISOString().split('T')[0];

  // 检查是否有预约且状态为 confirmed、pending 或 completed
  const hasBookedAppointment = appointments.value.some(appointment => {
    const appointmentDate = new Date(appointment.start_time).toISOString().split('T')[0];
    return appointmentDate === d &&
           ['confirmed', 'pending', 'completed'].includes(appointment.status) &&
           appointment.counselor_id === selectedTherapist.value?.id;
  });

  // 如果日期不在可用日期列表中或有已预约的时段，则禁用该日期
  return !availableDates.value.includes(d) || hasBookedAppointment;
};

watch(selectedDate, (val) => {
  if (val) {
    const d = new Date(val).toISOString().split('T')[0];
    timeSlots.value = counselorFreeTimeMap.value[d] || [];
    selectedTime.value = null;
  } else {
    timeSlots.value = [];
    selectedTime.value = null;
  }
});

const isTimeAvailable = (time) => {
  if (!timeSlots.value.includes(time)) {
    return false;
  }

  // 检查该时间段是否已被预约
  const selectedDateStr = new Date(selectedDate.value).toISOString().split('T')[0];
  const [startTime] = time.split('-');
  const appointmentDateTime = `${selectedDateStr}T${startTime}:00`;

  // 检查是否有相同时间段的预约
  const hasBookedTimeSlot = appointments.value.some(appointment => {
    const appointmentDate = new Date(appointment.start_time).toISOString();
    return appointmentDate === appointmentDateTime &&
           ['confirmed', 'pending', 'completed'].includes(appointment.status) &&
           appointment.counselor_id === selectedTherapist.value?.id;
  });

  return !hasBookedTimeSlot;
};

const handleSubmit = async () => {
  if (
    !selectedDate.value ||
    !selectedTime.value ||
    !selectedTherapist.value ||
    !contactInfo.value.phone
  ) {
    if (!selectedTherapist.value) {
      ElMessage.error('请选择咨询师');
    } else {
      ElMessage.error('请填写完整信息');
    }
    return;
  }
  try {
    const appointmentDateStr = new Date(selectedDate.value).toISOString().split('T')[0];
    const startTime = selectedTime.value.split('-')[0];
    const appointmentDateTime = `${appointmentDateStr}T${startTime}:00`;

    const payload = {
      user_id: userStore.user.id,
      reason: problemDescription.value,
      counselor_or_assistant_id: selectedTherapist.value.id,
      room_number: roomNumber, // 固定为1
      appointment_date: appointmentDateTime,
      duration: 60,
      appointments_phone: contactInfo.value.phone
    };

    const response = await Api.bookConsultationRoom(payload);
    if (response.data.status === 201) {
      ElMessage.success('预约成功！');
    } else {
      ElMessage.error(response.data.message || '预约失败');
    }
  } catch {
    ElMessage.error('预约失败，请稍后再试');
  }
}
</script>

<style scoped>
.booking-page {
  /*max-width: 800px;
  margin: 40px auto;
  padding: 20px;*/
}

.banner {
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('/articles-banner.jpg');
  background-size: cover;
  background-position: center;
  color: white;
  text-align: center;
  padding: 4rem 1rem;
}

h1 {
  text-align: center;
  font-size: 2rem;
  margin-bottom: 10px;
}

p {
  text-align: center;
  color: #e3dfdf;
  margin-bottom: 20px;
}

.tabs {
  margin-bottom: 20px;
}

.therapist-scroll-section {
  margin-bottom: 20px;
}

.therapist-scroll-section h3 {
  margin-bottom: 10px;
}

.therapist-container {
  position: relative;
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 0 50px;
  width: 100%;
  margin: 20px 0;
}

.scrollbar-wrapper {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  scroll-behavior: smooth;
  -webkit-overflow-scrolling: touch;
}

.therapist-list {
  display: flex;
  flex-wrap: nowrap;
  gap: 20px;
  padding: 20px;
  min-width: min-content;
  width: max-content;
}

.therapist-card {
  flex: 0 0 auto;
  width: 250px;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 1.5rem;
  text-align: center;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.therapist-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
}

.therapist-card.selected {
  background-color: #e0f7fa;
  border-color: #29b6f6;
}

.therapist-card img {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  margin-bottom: 1rem;
  object-fit: cover;
}

.scroll-button {
  position: absolute;
  z-index: 1;
  background: none;
  border: none;
  width: 44px;
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  cursor: pointer;
}

.scroll-button.left {
  left: 0;
}

.scroll-button.right {
  right: 0;
}

.scroll-button:hover {
  transform: scale(1.1);
}

.scroll-button:active {
  transform: scale(0.95);
}

.scroll-button :deep(.el-icon) {
  font-size: 24px;
  color: #606266;
}

.booking-container {
  display: flex;
  gap: 20px;
  align-items: flex-start;
}

.calendar-section {
  flex: 2;
  margin-right: 30px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.calendar {
  flex-grow: 1;
}

.details-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.time-slots {
  margin-top: 10px;
}

.time-slots h4 {
  margin-bottom: 10px;
}

.additional-info {
  margin-top: 20px;
}

.additional-info h3 {
  margin-bottom: 10px;
}

.footer {
  margin-top: 20px;
  text-align: center;
}

.footer .price {
  color: #4caf50;
  font-weight: bold;
}

.el-button {
  margin: 5px 0;
}
</style>
